#!/bin/bash

#set -x

CPU_CORES=`cat /proc/cpuinfo | grep -i "cpu core"|uniq|gawk -F':' '{ print $2 }'`

ROOT_DIR=$PWD
BUILD_DIR=${ROOT_DIR}/build

quit="no"
is_done="no"
build_type="Debug"

if [ "$1" = 'r' ]; then
    build_type="RelWithDebInfo"
fi

#------------------------------------------------------------------------------
function build_client {
    tool_file=${ROOT_DIR}/toolchain_files/toolchain_linux_board.cmake 
    cd $BUILD_DIR
    rm -rf *
    cmake -DBUILD_JUST=client -DCMAKE_BUILD_TYPE=${build_type} -DCMAKE_TOOLCHAIN_FILE=${tool_file} .. 
    if [ $? = 0 ]; then
        make VERBOSE=1 -j${CPU_CORES}
    fi
}
#------------------------------------------------------------------------------
function build_server {
    cd $BUILD_DIR
    rm -rf *
    cmake -DUNITTEST=ON -DBUILD_JUST=server -DCMAKE_BUILD_TYPE=${build_type} .. 
    if [ $? = 0 ]; then
        make VERBOSE=1 -j${CPU_CORES}
    fi
}
#------------------------------------------------------------------------------
# main
#------------------------------------------------------------------------------
if [ $? = 0 ]; then
    
    while [ $quit != "yes" ]
    do
        echo "*************************"
        echo "  teletype build helper"
        echo "*************************"
        echo
        echo "    1. client"
        echo "    2. server"
        echo "    3. quit"
        echo
        echo -n "Your choice? : "
        read choice
        
        case $choice in
            1) build_client ;;
            2) build_server ;;
            3) quit="yes" ;;
            *) echo "\n  \"$choice\" is not valid.\n\n\n" 
            sleep 1 ;;
        esac
        
        if [ "$is_done" = "yes" ]; then
            break
        fi
    done
fi
